package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"strconv"
	"time"
	"xiaomi-mgmt/cache"
	"xiaomi-mgmt/models"
)

func Comment(c *gin.Context) {
	content := c.PostForm("content")
	good_id, _ := strconv.Atoi(c.PostForm("good_id"))
	user_id, _ := strconv.Atoi(c.PostForm("user_id"))
	if content == "" || good_id == 0 || user_id == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.Comment{
		Model:   gorm.Model{},
		Content: content,
		GoodId:  good_id,
		UserId:  user_id,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "评论失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "评论成功",
	})
	return
}

func CommentList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var comment []models.Comment
	redis_key := "list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&comment)
		jsonData, _ := json.Marshal(comment)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &comment)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": comment,
	})
	return
}
